package com.zg.autoflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.autoflow.service.SettleWorkflowStepSubService;
import com.zg.common.core.dao.autoflow.dao.SettleWorkflowStepSubDao;
import com.zg.common.core.dao.autoflow.dao.SettleWorkflowSubDao;
import com.zg.common.core.dao.autoflow.entity.SettleWorkflowInstance;
import com.zg.common.core.dao.autoflow.entity.SettleWorkflowStepSub;
import com.zg.common.core.dao.autoflow.entity.SettleWorkflowSub;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author zg
*/
@Service
@RequiredArgsConstructor
public class SettleWorkflowStepSubServiceImpl implements SettleWorkflowStepSubService {

    private final SettleWorkflowSubDao settleWorkflowSubDao;
    private final SettleWorkflowStepSubDao settleWorkflowStepSubDao;

    @Override
    public SettleWorkflowStepSub getCurSubFlowStepSub(SettleWorkflowInstance selectedWorkflowInstance, String stepCode) {
        LambdaQueryWrapper<SettleWorkflowSub> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SettleWorkflowSub::getFlowCode, selectedWorkflowInstance.getFlowCode());
        List<SettleWorkflowSub> list = settleWorkflowSubDao.list(queryWrapper);
        if (list.size() == 0) {
            return null;
        }

        //挨个匹配子流程
        for (SettleWorkflowSub f : list) {

            //匹配字段
            if(StringUtils.isNotBlank(f.getField()) && StringUtils.isNotBlank(f.getFieldValue()))
            {
                if (!f.getFieldValue().equals(selectedWorkflowInstance.getDefValue(f.getField()))) {
                    continue;
                }
            }
            if(StringUtils.isNotBlank(f.getField2()) && StringUtils.isNotBlank(f.getField2Value()))
            {
                if (!f.getField2Value().equals(selectedWorkflowInstance.getDefValue(f.getField2()))) {
                    continue;
                }
            }

            //找到里合理的子流程 然后就看这个流程的环节 是否能匹配
            //在这个子流程里找到这个环节
            LambdaQueryWrapper<SettleWorkflowStepSub> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SettleWorkflowStepSub::getSubFlowId, f.getId())
                    .eq(SettleWorkflowStepSub::getStepNo, stepCode);
            SettleWorkflowStepSub one = settleWorkflowStepSubDao.getOne(queryWrapper1);
            if(one!=null)
            {
                return one;
            }
        }
        return null;
    }
}
